package com.lanyun.carworld.controller.user;


import com.lanyun.carworld.common.BaseResponse;
import com.lanyun.carworld.common.ResultUtils;
import com.lanyun.carworld.utils.AliOssUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件
 */

@RestController
@RequestMapping("/user/file")
@Api(tags = "文件")
@Slf4j
public class FileController {

    //阿里云oss工具类
    @Resource
    private AliOssUtil aliOssUtil;
    /**
     * 上传文件
     *
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile file) throws IOException {
        log.info("上传文件:{}", file);


        String originalFilename = file.getOriginalFilename();//得到上传时原始文件的名称
        //截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构建新文件名称        UUID是java自带的，目的生成不一样的名称
        String objectName = UUID.randomUUID().toString() + extension;
        //文件请求路径
        String filePath = aliOssUtil.upload(file.getBytes(), objectName);//(原文件名byte数组,传上去的名称)
        log.info("文件上传完成，{}", file);
        log.info("文件路径:{}", filePath);

        //截取路径
        return ResultUtils.success(filePath);
    }
}











